package com.oot.twitter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener;
import com.oot.twitter.Twitter.TweetItem;
import com.oot.twitter.info.Tweet;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class Tweets extends Activity implements OnClickListener {
	
	public ArrayList<TweetItem> m_tweet_item =null;
	public UserTweetsListAdapter m_adapter;
	
	PullToRefreshListView list;
	
	public String user_id;
	public String type;
	View footerView;
	ProgressBar progress;
	
	int item_position_clicked = -1;
	
	int old = 0;
	boolean loading = true,isGetMore = true;
	int old_post = -1,curret_postion = -1;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.tweets);
        
        Bundle receive = this.getIntent().getExtras();
        this.user_id = receive.getString("user_id");
        this.type = receive.getString("type");
        
        TextView header = (TextView)findViewById(R.id.tweets_text_header);
        if(this.type.equals("favorites"))
        {
        	header.setText("Favorites");
        }
        
        LinearLayout new_tweet = (LinearLayout)findViewById(R.id.me_twitter_new_tweet);
        new_tweet.setOnClickListener(this);
        
        initializeData();
    }

    public void initializeData()
    {
    	//Get data from Server
    	StringBuilder builder = new StringBuilder();
    	HttpGet httpGet;
    	if(this.type.equals("tweets"))
    		httpGet = new HttpGet(ConnectionTwitter.SERVER_URL+"/api/tweet/user_timeline?user_id="+this.user_id);
    	else
    		httpGet = new HttpGet(ConnectionTwitter.SERVER_URL+"api/user/favorites?user_id="+this.user_id);
    	try{
    			HttpResponse response = GlobalData.client.execute(httpGet);
    			StatusLine statusLine = response.getStatusLine();
    		
    			int statusCode = statusLine.getStatusCode();
    			if (statusCode == 200) {
    				HttpEntity entity = response.getEntity();
    				InputStream content = entity.getContent();
    				BufferedReader reader = new BufferedReader(
    						new InputStreamReader(content));
    				String line;
    				while ((line = reader.readLine()) != null) {
    					builder.append(line);
    				}
    			} else {
    				Log.e(Twitter.class.toString(), "Failed to download JSON string");
    			}			
    		
    	}catch(Exception e)
    	{
    		e.printStackTrace();
    	}					
		
    	//System.out.println(builder.toString());    	    	
    	
    	m_tweet_item = new ArrayList<TweetItem>();
    	try{
    		JSONArray jsonArray = new JSONArray(builder.toString());
    		System.out.println("Length = "+jsonArray.length());
    		for(int i = 0;i < jsonArray.length(); i++)
    		{
    			JSONObject jsonObject = jsonArray.getJSONObject(i);
    			Bitmap bitmap = null;
    			//System.out.println(jsonObject.getString("tweet_id")+"|"+jsonObject.getString("content")+"|"+jsonObject.getString("created_time")+"|"+jsonObject.getString("username")+"|"+jsonObject.getString("full_name")+jsonObject.getString("avatar"));
   			 	try {
   			 		bitmap = BitmapFactory.decodeStream((InputStream)new URL(jsonObject.getString("avatar")).getContent());
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
   			 	if(i == 0)
   			 		GlobalData.tweets_maxid = jsonObject.getInt("tweet_id");   			 	
   			 	if(i == jsonArray.length() -1)
   			 	{
   			 		GlobalData.tweets_sinceid = jsonObject.getInt("tweet_id");
   			 	}
   			 	
    			TweetItem tweet_item = new TweetItem(jsonObject.getString("tweet_id"),jsonObject.getString("user_id"), jsonObject.getString("content"), jsonObject.getString("created_time"), jsonObject.getString("username"), jsonObject.getString("full_name"),bitmap ,jsonObject.getString("avatar"),jsonObject.getString("refav"),jsonObject.getString("retweeted_by"));
	    		if(Tweets.this.user_id.equals(jsonObject.getString("user_id")))
   	    			tweet_item.setMyseft(true);    			
    			m_tweet_item.add(tweet_item);
    		}
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace();
    	}
    	
    	this.m_adapter = new UserTweetsListAdapter(this, R.layout.tweet_item, m_tweet_item);
        list = (PullToRefreshListView)findViewById(R.id.tweets_list);
        setListEventHandler();
    	list.setAdapter(m_adapter);    	
    }

    //////////////  SET LIST EVENT HANDLER /////////////////
    public void setListEventHandler()
    {
        footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footerlistview, null, false);
        list.addFooterView(footerView);
        progress = (ProgressBar)findViewById(R.id.progressbar_more); 
        
        list.setOnRefreshListener(new OnRefreshListener() {
            public void onRefresh() {
                // Do work to refresh the list here.
            	new GetNewData().execute(new String[]{"ABCD"});
            	m_adapter.notifyDataSetChanged();
            }
        });
    	list.setAdapter(m_adapter);    	
    	
    	///////////////////// ITEM CLICK EVENT ////////////////////////////
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> adapterView, View view, int postion, long l) {
                // Prepare param
                //tweet_id, content, created_time, parent_id, user_id, username, full_name, avatar, refav, retweeted_by;
            	//System.out.println("OOT|"+postion+"|"+m_tweet_item.get(postion).getContent());
            	if(postion != old_post)
            	{
            		item_position_clicked = postion;
            		Tweet tweet = new Tweet();
            		tweet.setContent(m_tweet_item.get(postion - 1).getContent());
            		tweet.setFull_name(m_tweet_item.get(postion -1).getFullname());
            		tweet.setRefav(m_tweet_item.get(postion -1).getRefav());
            		tweet.setTweet_id(m_tweet_item.get(postion -1).getID());

            		tweet.setCreated_time(m_tweet_item.get(postion -1).getCreatedTime());
            		tweet.setParent_id(m_tweet_item.get(postion -1).getParentID());
            		tweet.setAvatar(m_tweet_item.get(postion -1).getAvatar());
            		tweet.setUsername(m_tweet_item.get(postion -1).getUsername());
            		GlobalData.paramIntent = tweet;
                
            		Intent tweetInfo = new Intent(Tweets.this, TweetInfo.class);
            		startActivityForResult(tweetInfo, 0);
            	}
            }
        });
        
        
        ///////////////////////////////////////////////////////////////////
        ///////////////////// ITEM LONG CLICK EVENT ///////////////////////
        ////////////////////////////////////////////////////////////////////
        list.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> parent, View view,int postion, long l) {
				// TODO Auto-generated method stub
				if(old_post != -1)
				{
					m_tweet_item.get(old_post -1).setIsLongClick(false);
					m_adapter.notifyDataSetChanged();
				}
				LinearLayout onlayout = (LinearLayout)view.findViewById(R.id.timeline_mainparent);
				m_tweet_item.get(postion -1).setHeight(onlayout.getHeight());
				
				m_tweet_item.get(postion -1).setIsLongClick(true);
				m_adapter.notifyDataSetChanged();
				
				old_post = postion;
				return true;
			}
        	
		});
    	
        
        ///////////////////////////////////////////////////////////////////////////
        /////////////////////// LOAD MORE TWEET HANDLER ///////////////////////////
        ///////////////////////////////////////////////////////////////////////////
    	list.setOnScrollListener(new OnScrollListener() {	//Load More item when endless scroll	
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
			}
			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				//System.out.println("ON SCROLL | "+on_scroll);
				boolean loadmore = (firstVisibleItem + visibleItemCount >= totalItemCount);
				
				if(loadmore && isGetMore && loading)
				{
						//System.out.println("GET MORE ITEM");					
						Thread thread = new Thread(null,loadMoreListItems);
						thread.start();
				}

			}
		});    	
    	
    }
    
    

    ArrayList<TweetItem> more;
    
    private Runnable loadMoreListItems = new Runnable() {
		public void run() {
			// TODO Auto-generated method stub
			isGetMore = false;
			more = new ArrayList<TweetItem>();
	    	StringBuilder builder = new StringBuilder();   
	    	HttpGet httpGet;
	    	if(Tweets.this.type.equals("tweets"))
	    		httpGet = new HttpGet(ConnectionTwitter.SERVER_URL+"api/tweet/user_timeline?since_id="+GlobalData.tweets_sinceid);
	    	else
	    		httpGet = new HttpGet(ConnectionTwitter.SERVER_URL+"api/user/favorites?user_id="+Tweets.this.user_id+"&since_id="+GlobalData.tweets_sinceid);
	    	//System.out.println(ConnectionTwitter.SERVER_URL+"api/tweet/home_timeline?since_id="+GlobalData.timeline_sinceid);
	    	try{
	    			HttpResponse response = GlobalData.client.execute(httpGet);
	    			StatusLine statusLine = response.getStatusLine();	
	    			int statusCode = statusLine.getStatusCode();
	    			if (statusCode == 200) {
	    				HttpEntity entity = response.getEntity();
	    				InputStream content = entity.getContent();
	    				BufferedReader reader = new BufferedReader(
	    						new InputStreamReader(content));
	    				String line;
	    				while ((line = reader.readLine()) != null) {
	    					builder.append(line);
	    				}
	    			} else {
	    				Log.e(Twitter.class.toString(), "Failed to download JSON string");
	    			}			
	    		
	    	}catch(Exception e)
	    	{
	    		e.printStackTrace();
	    	}	
	    	
	    	if(builder.toString().length()>5)
	    	{
	    		try{
	    			JSONArray jsonArray = new JSONArray(builder.toString());
	    			//System.out.println("MORE LENGTH = "+jsonArray.length());
	    			for(int i = 0;i < jsonArray.length(); i++)
	    			{
	    				JSONObject jsonObject = jsonArray.getJSONObject(i);
	    				Bitmap bitmap = null;
	    				//System.out.println(jsonObject.getString("tweet_id")+"|"+jsonObject.getString("content")+"|"+jsonObject.getString("created_time")+"|"+jsonObject.getString("username")+"|"+jsonObject.getString("full_name")+jsonObject.getString("avatar"));
	   			 		try {
	   			 			bitmap = BitmapFactory.decodeStream((InputStream)new URL(jsonObject.getString("avatar")).getContent());
	   			 		} catch (MalformedURLException e) {
	   			 			// TODO Auto-generated catch block
	   			 			e.printStackTrace();
	   			 		} catch (IOException e) {
	   			 			// TODO Auto-generated catch block
	   			 			e.printStackTrace();
	   			 		}
	   			 		
	   			 		if( i == jsonArray.length() - 1)
	   			 		{
	   			 			old = GlobalData.timeline_sinceid;
	   			 			GlobalData.timeline_sinceid = jsonObject.getInt("tweet_id");
	   			 		}
	   			 	
		    			TweetItem tweet_item = new TweetItem(jsonObject.getString("tweet_id"),jsonObject.getString("user_id"), jsonObject.getString("content"), jsonObject.getString("created_time"), jsonObject.getString("username"), jsonObject.getString("full_name"),bitmap ,jsonObject.getString("avatar"),jsonObject.getString("refav"),jsonObject.getString("retweeted_by"));
	   	    			if(Tweets.this.user_id.equals(jsonObject.getString("user_id")))
	   	    				tweet_item.setMyseft(true);
	   			 		more.add(tweet_item);
	    			}
	    		}
	    		catch(Exception e)
	    		{
	    			e.printStackTrace();
	    		}
	    	}
	    	else
	    	{
	    		System.out.println("Hahahahaha");
	    		loading = false;
	    		progress.setVisibility(View.INVISIBLE);
	    		isGetMore = false;
	    	}	
	    	
		    //System.out.println("SINCE ID 2 = "+GlobalData.timeline_sinceid+"|OLD="+old);
	    	runOnUiThread(returnRes);
	    	
		}
	};    
	private Runnable returnRes = new Runnable() {		
		public void run() {
			// TODO Auto-generated method stub
			if(more != null && more.size()>0)
			{
				for(int i = 0; i< more.size(); i++)
				{
					m_tweet_item.add(more.get(i));
				}
			}

			m_adapter.notifyDataSetChanged();
			list.onRefreshComplete();
			isGetMore = true;
		}
	};    
    
    @Override
    protected void onResume()
    {
    	super.onResume();
    	System.out.println("OnResume Called !!!");
    	m_adapter.notifyDataSetChanged();
    }    
    
    ///////////////FAVORITES - UNFAVORITE/////////////////////////
    public boolean acFav(TweetItem item){
    	//Get data from Server
    	boolean return_value = false;
    	StringBuilder builder = new StringBuilder();
    	HttpPost httpPost;
    	if(item.getRefav().equals("10") || item.getRefav().equals("11"))
    	{
    		httpPost = new HttpPost(ConnectionTwitter.UNFAVORITE_URL+"?tweet_id="+item.getID());
    	}
    	else
    	{
    		httpPost = new HttpPost(ConnectionTwitter.FAVORITE_URL+"?tweet_id="+item.getID());
    	}
    	try{
			HttpResponse response = GlobalData.client.execute(httpPost);
			StatusLine statusLine = response.getStatusLine();
		
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				Log.e(Twitter.class.toString(), "Failed to download JSON string");
			}			
		
    	}catch(Exception e)
    	{
    		e.printStackTrace();
    	}
    	
    	String result = builder.toString();
    	result = "["+result+"]";
    	try {
    		JSONArray json = new JSONArray(result);
    		JSONObject jsonObject = json.getJSONObject(0);
    		String value = jsonObject.getString("result");
    		int res = Integer.parseInt(value);
    		if(res == 1) //Update Success
    			return_value = true;
    	}catch (JSONException e){ 
    		// TODO Auto-generated catch block		    		
    		e.printStackTrace();
    	}    	
    	
    	return return_value;
	}    
    
    /////////////////DESTROY TWEET /////////////////////////
    public boolean destroyTweet(TweetItem item)
    {
    	boolean return_value = false;
    	
    	StringBuilder builder = new StringBuilder();
    	HttpPost httpPost = new HttpPost(ConnectionTwitter.DESTROYTWEET+"?tweet_id="+item.getID());
    	try{
			HttpResponse response = GlobalData.client.execute(httpPost);
			StatusLine statusLine = response.getStatusLine();
		
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				Log.e(Twitter.class.toString(), "Failed to download JSON string");
			}			
		
    	}catch(Exception e)
    	{
    		e.printStackTrace();
    	}    	
    	String result = builder.toString();
    	result = "["+result+"]";
    	try {
    		JSONArray json = new JSONArray(result);
    		JSONObject jsonObject = json.getJSONObject(0);
    		String value = jsonObject.getString("result");
    		int res = Integer.parseInt(value);
    		if(res == 1) //Update Success
    			return_value = true;
    	}catch (JSONException e){ 
    		// TODO Auto-generated catch block		    		
    		e.printStackTrace();
    	}        	
    	
    	
    	return return_value;
    }    
    
    private class GetNewData extends AsyncTask<String,Void,String> {//Get New Data When Pull Scroll
        @Override
        protected void onPreExecute() 
        {
        	
        }  
		@Override
		protected String doInBackground(String... params) 
		{
			// TODO Auto-generated method stub
	    	StringBuilder builder = new StringBuilder();
	    	HttpGet httpGet;
	    	//HttpGet httpGet = new HttpGet(ConnectionTwitter.SERVER_URL+"api/tweet/user_timeline?max_id="+GlobalData.tweets_maxid);
	    	if(Tweets.this.type.equals("tweets"))
	    		httpGet = new HttpGet(ConnectionTwitter.SERVER_URL+"api/tweet/user_timeline?max_id="+GlobalData.tweets_maxid);
	    	else
	    		httpGet = new HttpGet(ConnectionTwitter.SERVER_URL+"api/user/favorites?user_id="+Tweets.this.user_id+"&max_id="+GlobalData.tweets_maxid);	    	
	    	try{
	    			HttpResponse response = GlobalData.client.execute(httpGet);
	    			StatusLine statusLine = response.getStatusLine();
	    		
	    			int statusCode = statusLine.getStatusCode();
	    			if (statusCode == 200) {
	    				HttpEntity entity = response.getEntity();
	    				InputStream content = entity.getContent();
	    				BufferedReader reader = new BufferedReader(new InputStreamReader(content));
	    				String line;
	    				while ((line = reader.readLine()) != null) {
	    					builder.append(line);
	    				}
	    			} else {
	    				Log.e(Twitter.class.toString(), "Failed to download JSON string");
	    			}			
	    		
	    	}catch(Exception e)
	    	{
	    		e.printStackTrace();
	    	}					
	    	
	    	try{
	    		JSONArray jsonArray = new JSONArray(builder.toString());
	    		System.out.println("Length refresh = "+jsonArray.length());
	    		for(int i = 0;i < jsonArray.length(); i++)
	    		{
	    			JSONObject jsonObject = jsonArray.getJSONObject(i);
	    			Bitmap bitmap = null;
	    			//System.out.println(jsonObject.getString("tweet_id")+"|"+jsonObject.getString("content")+"|"+jsonObject.getString("created_time")+"|"+jsonObject.getString("username")+"|"+jsonObject.getString("full_name")+jsonObject.getString("avatar"));
	   			 	try {
	   			 		bitmap = BitmapFactory.decodeStream((InputStream)new URL(jsonObject.getString("avatar")).getContent());
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	   			 	if( i == 0)
	   			 		GlobalData.tweets_maxid = jsonObject.getInt("tweet_id");
	   			 	
	    			TweetItem tweet_item = new TweetItem(jsonObject.getString("tweet_id"),jsonObject.getString("user_id"), jsonObject.getString("content"), jsonObject.getString("created_time"), jsonObject.getString("username"), jsonObject.getString("full_name"),bitmap ,jsonObject.getString("avatar"),jsonObject.getString("refav"),jsonObject.getString("retweeted_by"));
   	    			if(Tweets.this.user_id.equals(jsonObject.getString("user_id")))
   	    				tweet_item.setMyseft(true);	    			
	    			m_tweet_item.add(0,tweet_item);

	    		}
	    	}
	    	catch(Exception e)
	    	{
	    		e.printStackTrace();
	    	}			

			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			//System.out.println("Refrested");
			m_adapter.notifyDataSetChanged();
            list.onRefreshComplete();
            super.onPostExecute("a");
        }    	 
    }        
    
    
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId())
		{
			case R.id.me_twitter_new_tweet:
				Intent newtw = new Intent(Tweets.this,NewTweetDialog.class);
				startActivity(newtw);				
				break;
				
			default:
				break;
		}
	}      
    
    public class TweetItem{ //Descriptions
    	public String tweet_id;
    	public String content;
    	public String created_time;
    	public String username;
    	public String fullname;
    	public Bitmap avarta_url;
    	public String avatar;
    	public String parent_id;
    	public String retweeted_by;
    	public String refav;
    	public String user_id;
    	public boolean is_longclick = false;
    	public boolean myseflt = false;  
    	public int height;
    	public TweetItem(String tweet_id,String user_id,String content,String created_time,String username,String fullname,Bitmap img,String avatar,String refav,String retweeted_by)
    	{
    		this.tweet_id = tweet_id;
    		this.content = content;
    		this.created_time = created_time;
    		this.username = username;
    		this.fullname = fullname;
    		this.avarta_url = img;
    		this.refav = refav;
    		this.avatar = avatar;
    		this.user_id = user_id;
    		this.height = 0;
    		this.retweeted_by = retweeted_by;
    	}
    	public void setMyseft(boolean me)
    	{
    		this.myseflt = me;
    	}
    	public boolean isMySeft()
    	{
    		return this.myseflt;
    	}
    	public void setRefav(String refa)
    	{
    		this.refav = refa;
    	}
    	public void setIsLongClick(boolean is_long_click)
    	{
    		this.is_longclick = is_long_click;
    	}
    	public boolean isLongClick()
    	{
    		return this.is_longclick;
    	}
    	public String getUserID()
    	{
    		return this.user_id;
    	}
    	public String getID()
    	{
    		return this.tweet_id;
    	}
    	public String getContent()
    	{
    		return this.content;
    	}
    	public String getCreatedTime()
    	{
    		return this.created_time;
    	}
    	public String getUsername()
    	{
    		return this.username;
    	}
    	public String getFullname()
    	{
    		return this.fullname;
    	}
    	public Bitmap getAvarta()
    	{
    		return this.avarta_url;
    	}
    	public String getAvatar()
    	{
    		return this.avatar;
    	}
    	public String getParentID()
    	{
    		return this.parent_id;
    	}
    	public String getRefav()
    	{
    		return this.refav;
    	}
    	public int getHeight()
    	{
    		return this.height;
    	}
    	public void setHeight(int height)
    	{
    		this.height = height;
    	}   
    	public String getRetweetedBy()
    	{
    		return this.retweeted_by;
    	}    	
    }
    private class UserTweetsListAdapter extends ArrayAdapter<TweetItem>{
    	private ArrayList<TweetItem> items;
    	public UserTweetsListAdapter(Context context, int textViewResourceId, ArrayList<TweetItem> items)
    	{
    		super(context, textViewResourceId,items);
    		this.items = items;
    	}
    	
    	@Override
    	public int getViewTypeCount() {
    	    return 12;
    	  }
        @Override
        public int getItemViewType(int position) {
        	String type = this.items.get(position).getRefav();
        	if(type.equals("0")) //Normal Tweets
        		return 0;
        	else if(type.equals("1")) //Retweet
        		return 1;
        	else if(type.equals("10")) //Favorites
        		return 10;
        	else   						//Retweet and Favorites
        		return 11;
        }  
        
    	@Override
    	public View getView(int position, View v, ViewGroup parent) 
    	{    
    		
    		if(v == null)
    		{
    			LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			v = vi.inflate(R.layout.tweet_item,null);
    		}
    		
    		final TweetItem tweet_item = items.get(position);
    		final int pos = position;
    		
    		if(tweet_item!= null)
    		{
    			
    			if(tweet_item.isLongClick()) //Long click handler
    			{
    				LinearLayout longlayout = (LinearLayout)v.findViewById(R.id.timeline_onlongclick);
    				LinearLayout onlayout = (LinearLayout)v.findViewById(R.id.timeline_mainparent);
    				
    				longlayout.setVisibility(View.VISIBLE);
    				LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, tweet_item.getHeight());
    				longlayout.setLayoutParams(param);
    				//System.out.println(tweet_item.getHeight());
    				onlayout.setVisibility(View.GONE);
    				
    				LinearLayout de = (LinearLayout)v.findViewById(R.id.tweet_item_delete);
    				ImageView rt = (ImageView)v.findViewById(R.id.rtImg);
    				final ImageView fav = (ImageView)v.findViewById(R.id.faveImg);
    				ImageView rep = (ImageView)v.findViewById(R.id.replyImg);
    				ImageView retw  = (ImageView)v.findViewById(R.id.rtImg);
    				ImageView share = (ImageView)v.findViewById(R.id.tweet_item_share);
    				
    				if(tweet_item.getRefav().equals("10") || tweet_item.getRefav().equals("11"))
    				{
    					fav.setImageResource(R.drawable.ic_action_fave_on_default);
    				}
    				else
    				{
    					fav.setImageResource(R.drawable.ic_action_fave_off_default);
    				}
    				
    				
    				//Retweet
    				retw.setOnClickListener(new OnClickListener() {
    					public void onClick(View v) {
    						// TODO Auto-generated method stub
							System.out.println("AAAAAABB");
							if (tweet_item.getUserID() == GlobalData.user_id)
								return;
							String message, button1;
							// Get retweet value
							int refav = Integer.parseInt(tweet_item.getRefav()) %10;
							if (refav == 0){
								message = "Retweet this to your followers ?";
								button1 = "Retweet"; 
							}
							else{
								message = "Undo this retweet ?";
								button1 = "Undo";
							}
								
							AlertDialog.Builder builder  = new AlertDialog.Builder(Tweets.this);
							builder.setTitle("Retweet");
							builder.setMessage(message);
							builder.setPositiveButton(button1, new DialogInterface.OnClickListener() {						
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									String requestString;
									int refav = Integer.parseInt(tweet_item.getRefav()) %10;
									if (refav == 0){
										requestString = ConnectionTwitter.SERVER_URL+"api/tweet/retweet?tweet_id="+tweet_item.getID();
									}
									else
										requestString = ConnectionTwitter.SERVER_URL+"api/tweet/unretweet?tweet_id="+tweet_item.getID();
									if (ConnectionTwitter.sendRequest(requestString) != null)
									{
										//Change Image Refav
										if(refav == 0) //Retweet
										{
											if(tweet_item.getRefav().equals("0"))
												tweet_item.setRefav("1");
											if(tweet_item.getRefav().equals("10"))
												tweet_item.setRefav("11");
										}
										else //UnRetweet
										{
											if(tweet_item.getRefav().equals("1"))
												tweet_item.setRefav("0");
											if(tweet_item.getRefav().equals("11"))
												tweet_item.setRefav("10");											
										}
										//System.out.println(tweet_item.getRefav()+"|"+"AT");
    									tweet_item.setIsLongClick(false);
    									old_post = -1;
    									m_adapter.notifyDataSetChanged();										
									}									
								}
							})
							.setNeutralButton("Quote", new DialogInterface.OnClickListener() {						
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
		    						m_tweet_item.get(pos).setIsLongClick(false);
		    						m_adapter.notifyDataSetChanged();
		    						
		    						String quote = m_tweet_item.get(pos).getContent();
		    						quote = "\""+quote+"\"";
		    						Intent quote_intent = new Intent(Tweets.this,NewTweetDialog.class);
		    						Bundle bund = new Bundle();
		    						bund.putString("mentions", quote);
		    						bund.putString("tweet_id", m_tweet_item.get(pos).getID());
		    						quote_intent.putExtras(bund);
		    						startActivity(quote_intent);		
		    						
								}
							})
							.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							});
							builder.show();   						
    					}
    				});    				
  				
    				//Share
					share.setOnClickListener(new OnClickListener() {
						public void onClick(View view) {
							shareAction(tweet_item.getContent());
						}
					});    				
    				// Reply 
    				rep.setOnClickListener(new OnClickListener() {					
    					public void onClick(View arg0) {
    						// TODO Auto-generated method stub
    						//lay.setVisibility(View.VISIBLE);
    						//lin.setVisibility(View.GONE);	
    						m_tweet_item.get(pos).setIsLongClick(false);
    						m_adapter.notifyDataSetChanged();
    						
    						String content = m_tweet_item.get(pos).getContent();
    						String mentions = "";
    						for(int i = 0; i< content.length();i++)
    						{
    							if(content.charAt(i) == '@')
    							{
    								int j = i;
    								while(content.charAt(j) != ' ')
    								{
    									j++;
    								}
    								mentions += content.substring(i, j);
    								mentions += " "; 
    							}
    						}
    						mentions = mentions + "@"+m_tweet_item.get(pos).getUsername();
    						Intent reply_intent = new Intent(Tweets.this,NewTweetDialog.class);
    						Bundle bun = new Bundle();
    						bun.putString("mentions", mentions);
    						bun.putString("tweet_id", m_tweet_item.get(pos).getID());
    						reply_intent.putExtras(bun);
    						startActivity(reply_intent);
    						
    					}
    				});    				
    				
    				// Favorite - Unfavorite
    				fav.setOnClickListener(new OnClickListener() {				
    					public void onClick(View v) {
    						// TODO Auto-generated method stub
    						if(tweet_item.getRefav().equals("10") || tweet_item.getRefav().equals("11")) //Unfavorite
    						{
    								if(acFav(tweet_item))
    								{		
    									fav.setImageResource(R.drawable.ic_action_fave_off_default);
    									if(tweet_item.getRefav().equals("10"))
    									{
    										tweet_item.setRefav("0");
    										//refav.setVisibility(View.INVISIBLE);
    									}
    									if(tweet_item.equals("11"))
    									{
    										tweet_item.setRefav("1");
    									}
    									old_post = -1;
    									tweet_item.setIsLongClick(false);
    									m_adapter.notifyDataSetChanged();
    								}
    						}
    						else //Favorite
    						{
    								if(acFav(tweet_item))
    								{

    									//System.out.println("Favorited");
    									fav.setImageResource(R.drawable.ic_action_fave_on_default);
    									if(tweet_item.getRefav().equals("0"))
    									{
    										tweet_item.setRefav("10");
    									}
    									if(tweet_item.equals("1"))
    									{
    										tweet_item.setRefav("11");
    									}
    									old_post = -1;
    									tweet_item.setIsLongClick(false);
    									m_adapter.notifyDataSetChanged();
    								}
    						}
    						
    					}
    					
    				});			   				

    				if(tweet_item.isMySeft()) // This tweet is myseft
    				{
    					de.setVisibility(View.VISIBLE);
    					ImageView imgDel = (ImageView)v.findViewById(R.id.delImg);
    					
    					//Delete Tweet
    					imgDel.setOnClickListener(new OnClickListener() {
    						public void onClick(View v) {
    							// TODO Auto-generated method stub
    							AlertDialog.Builder builder  = new AlertDialog.Builder(Tweets.this);
    							builder.setTitle("Delete");
    							builder.setMessage("Do you want to delete this Tweet?");
    							builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {						
    								public void onClick(DialogInterface dialog, int which) {
    									// TODO Auto-generated method stub
    									if(destroyTweet(tweet_item))
    									{
    										m_tweet_item.remove(pos);
    										m_adapter.notifyDataSetChanged();
    										dialog.dismiss();
    									}
    								}
    							})
    							.setNegativeButton("No", new DialogInterface.OnClickListener() {
    								public void onClick(DialogInterface dialog, int which) {
    									// TODO Auto-generated method stub
    									dialog.dismiss();
    								}
    							});
    							builder.show();
    						}
    					});
    					
    				}
    				else
    				{
    					
    					de.setVisibility(View.GONE);
    					if(tweet_item.getRefav().equals("1") || tweet_item.getRefav().equals("11"))
    						rt.setBackgroundResource(R.drawable.ic_action_rt_on_default);
    					else
    						rt.setImageResource(R.drawable.ic_action_rt_off_default);
    				}
    				
    			}
    			else
    			{
    				LinearLayout longlayout = (LinearLayout)v.findViewById(R.id.timeline_onlongclick);
    				LinearLayout onlayout = (LinearLayout)v.findViewById(R.id.timeline_mainparent);
    				
    				longlayout.setVisibility(View.GONE);
    				onlayout.setVisibility(View.VISIBLE); 
    				
    				RelativeLayout rtwed = (RelativeLayout)v.findViewById(R.id.retweeted_by_layout);
    				ImageView imgview = (ImageView)v.findViewById(R.id.timeline_avarta);
    				TextView fullname = (TextView)v.findViewById(R.id.timeline_fullname);
    				TextView username = (TextView)v.findViewById(R.id.timeline_username);
    				TextView content = (TextView)v.findViewById(R.id.timeline_content);
    				TextView time = (TextView)v.findViewById(R.id.timeline_time);
    				
    				ImageView refav = (ImageView)v.findViewById(R.id.timeline_refav);
    				
    				if(tweet_item.getRetweetedBy().equals(""))
    					rtwed.setVisibility(View.GONE);
    				else
    				{
    					TextView rtwedby = (TextView)v.findViewById(R.id.retweeted_by);
    					rtwedby.setText("Retweeted by "+tweet_item.getRetweetedBy());
    				}
    				
    				switch(getItemViewType(position))
    				{
    					case 0 : 
    						
    						break;
    					case 1 :
    						refav.setImageResource(R.drawable.ic_dogear_rt);
    						break;
    					case 10 : 
    						refav.setImageResource(R.drawable.ic_dogear_fave);
    						break;
    					case 11:
    						refav.setImageResource(R.drawable.ic_dogear_both);
    						break;
    				}
    				
    				fullname.setText(tweet_item.getFullname());
    				username.setText("@"+tweet_item.getUsername());
    				content.setText(tweet_item.getContent());
    				time.setText(tweet_item.getCreatedTime());
    				GlobalData.imageLoader.DisplayImage(tweet_item.getAvatar(), imgview);
    				//imgview.setImageBitmap(ImageHelper.getRoundedCornerBitmap(tweet_item.getAvarta(), 5));
    			}
    		}
    		
    		return v;
    	}
    	
    }
	private void shareAction(String content) {
		//create the send intent
		Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
		//set the type
		shareIntent.setType("text/plain");
		//add a subject
		shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Share");
		//build the body of the message to be shared
		String shareMessage = content;
		//add the message
		shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareMessage);
		//start the chooser for sharing
		startActivity(Intent.createChooser(shareIntent,"Share"));
	}  
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == 0)
		{
			if(data != null)
			{
				Bundle receive = data.getExtras();
				m_tweet_item.get(item_position_clicked - 1).setRefav(receive.getString("refav"));
				m_adapter.notifyDataSetChanged();
			}
		}
	}	
}
